using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Windows.Forms;
using CCWin;
using Newtonsoft.Json;

namespace Mes.质检管理.MaterialChenck
{
    // 原料质检新增窗体（使用 CSkin）
    public partial class MaterialCheckAdd : Skin_DevExpress
    {
        private const string ADD_URL = "/api/Inspection/AddChenck"; // 添加接口

        public MaterialCheckAdd()
        {
            InitializeComponent();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            try
            {
                if (string.IsNullOrWhiteSpace(txtInspectionNo?.SkinTxt.Text))
                {
                    txtInspectionNo.SkinTxt.Text = GenerateInspectionNo();
                    txtInspectionNo.ReadOnly = true;
                    txtInspectionNo.SkinTxt.ReadOnly = true;
                }
            }
            catch
            {
            }
        }

        private string GenerateInspectionNo()
        {
            var timePart = DateTime.Now.ToString("yyyyMMddHHmmss");
            var random = new Random(Guid.NewGuid().GetHashCode());
            var suffix = random.Next(0, 1000).ToString("D3");
            return $"ZJ{timePart}{suffix}";
        }

        // 点击保存：采集三个模块数据并调用接口
        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                // 1) 组装请求体字段，字段名与后端 AddInspectorBasicModelCommand 对齐
                var payload = new
                {
                    // 质检基本信息
                    InspectionNo = txtInspectionNo.SkinTxt.Text,
                    InspectionName = txtInspectionName.SkinTxt.Text,
                    InspectionDate = dtInspectionDate.Value.ToString("yyyy-MM-dd"),
                    Inspector = txtInspector.SkinTxt.Text,
                    Supplier = txtSupplier.SkinTxt.Text,

                    // 原料信息（此处 ProductId/InventoryInfoId/InspectionDetailId/InspectionInfoId 如后端必填请替换来源）
                    MaterialInfoId = 0,
                    ProductId = 0,
                    InventoryInfoId = 0,
                    InspectionDetailId = 0,

                    MaterialNo = txtMaterialNo.SkinTxt.Text,
                    MaterialName = txtMaterialName.SkinTxt.Text,
                    MaterialCategory = cboMaterialCategory.Text,
                    MaterialSize = cboMaterialSize.Text,
                    BatchTotalQuantity = ToInt(txtBatchTotalQuantity.SkinTxt.Text),
                    InspectionInfoId = 0,

                    // 质检明细
                    InspectionQuantity = ToInt(txtInspectionQuantity.SkinTxt.Text),
                    QualifiedQuantity = ToInt(txtQualifiedQuantity.SkinTxt.Text),
                    UnqualifiedQuantity = ToInt(txtUnqualifiedQuantity.SkinTxt.Text),
                    Inspectordetal = txtInspectorDetail.SkinTxt.Text,
                    Remarks = txtRemarks.SkinTxt.Text,
                    InspectionResult = cboInspectionResult.Text,
                    InspectionTableId = 0
                };

                var json = JsonConvert.SerializeObject(payload);

                // 使用HttpClient直接调用接口
                using (var httpClient = new HttpClient())
                {
                    // 设置超时时间
                    httpClient.Timeout = TimeSpan.FromSeconds(30);
                    
                    // 创建请求内容
                    var content = new StringContent(json, Encoding.UTF8, "application/json");
                    
                    // 发送POST请求
                    var response = httpClient.PostAsync("https://localhost:7149/api/Inspection/AddChenck", content).Result;
                    
                    // 检查响应状态
                    if (response.IsSuccessStatusCode)
                    {
                        MessageBox.Show("新增成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        DialogResult = DialogResult.OK;
                        Close();
                        return;
                    }
                    else
                    {
                        // 处理错误响应
                        string errorContent = response.Content.ReadAsStringAsync().Result;
                        MessageBox.Show($"保存失败：{response.StatusCode} - {errorContent}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }

                MessageBox.Show("保存失败，请稍后重试。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private int ToInt(string text)
        {
            int v; return int.TryParse(text, out v) ? v : 0;
        }

        // 取消
        private void btnCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            Close();
        }
    }
}
